package com.itheima.stock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.common.enums.ResponseCode;
import com.itheima.stock.domain.*;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.service.StockService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.resp.PageResult;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.StockInfo;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class StockServiceImpl implements StockService {

    /**
     *  这个对象中封装从配置文件中读取配置大盘编码信息数据
     * 这个对象中封装从配置文件中读取配置大盘编码信息数据
     */
    @Autowired
    private StockInfo stockInfo;

    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;

    /**
     * 股票板块信息Mapper接口
     */
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;

    /**
     * 股票信息Mapper接口
     */
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;




    @Override
    public R<List<StockUpdownDomain>> stockIncreaseLimit() {
        // 1. 参数校验
        // 2. 核心业务
        // 股票信息实时，肯定当前时间参数，数据库中数据早期采集数据，模拟时间
        // TODO
        Date curDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //mock数据
        String mockStr = "2021-12-27 09:47:00";
        curDateTime = DateTime.parse(mockStr, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        // TODO

        List<StockUpdownDomain> result = stockRtInfoMapper.selectStockUpDown(curDateTime);
        if (Objects.isNull(result) || result.isEmpty()) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        // 转换涨幅 [stream 流处理  jdk - 8 - 8的新特性 - stream ] 保留小数点后两位
        List<StockUpdownDomain> collect = result.stream().map((domain) -> {
            BigDecimal increase = domain.getIncrease();
            BigDecimal bigDecimal = increase.multiply(new BigDecimal(100));
            // 作业：保留小数点后两位
            domain.setIncrease(bigDecimal);
            return domain;
        }).collect(Collectors.toList());

        // 3. 数封装
        return R.ok(collect);
    }

    @Override
    public R<List<StockBlockRtInfoDomain>> sectorAll() {
        // 业务逻辑处理
        List<StockBlockRtInfoDomain> result = stockBlockRtInfoMapper.selectBlockAllLimit();
        // 数据封装返回
        if (Objects.isNull(result) || result.isEmpty()) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(result);
    }

    @Override
    public R<List<InnerMarketDomain>> innerIndexAll() {

        // 业务逻辑

        // 1. 读取配置文件中国内大盘编码数据
        List<String> innerMarketCode = stockInfo.getInner();
        // 2. 获取当前股票交易时刻 （注意：数据库老数据 参考讲义给出特定时间 ）
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        // mock time （模拟时间，仅限于开发测试阶段）
        //TODO 未完成
        String mockDate = "20211226105600";
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
        date = DateTime.parse(mockDate, formatter).toDate();
        // 3. 调用DAO 操作获取数据返回 （业务处理 SQL）
        List<InnerMarketDomain> result = stockMarketIndexInfoMapper.selectByIdsAndDate(innerMarketCode, date);
        if (Objects.isNull(result) || result.isEmpty()) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(result);
    }

    /**
     * 今日股票指数分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public R<PageResult<StockUpdownDomain>> stockGetLimit(Long page, Long pageSize) {
        pageAndPageSizeVerify(page, pageSize);
        PageHelper.startPage(page.intValue(),pageSize.intValue());
        //查询
        //TODO 未完成
        String mockDate = "20211226105600";
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
        Date date = DateTime.parse(mockDate, formatter).toDate();
        List<StockUpdownDomain> list = stockRtInfoMapper.selectStockToLimit(date);
        PageInfo<StockUpdownDomain> objectPageInfo = new PageInfo<>(list);
        PageResult<StockUpdownDomain> stockUpdownDomainPageResult = new PageResult<>(objectPageInfo);
        return R.ok(stockUpdownDomainPageResult);
    }

    private void pageAndPageSizeVerify(Long page, Long pageSize) {
        if (Objects.isNull(page)|| page <=0){
            page = 1L;
        }
        if (Objects.isNull(pageSize)|| pageSize <=0){
            pageSize = 20L;
        }
    }

    /**
     * 个股日K线详情
     * @return
     */
    @Override
    public R<List<Stock4EvrDayDomain>> getDayKLinData(String stockCode) {
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date lastDate = dateTime.toDate();
        Date pre20Day = dateTime.minusDays(20).toDate();

        String avlDate="20220106142500";
        lastDate = DateTime.parse(avlDate, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();
        String openDate="20220101093000";
        pre20Day = DateTime.parse(openDate, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();

        List<Stock4EvrDayDomain> result = stockRtInfoMapper.stockCreenDkLine(stockCode,pre20Day,lastDate);

        return R.ok(result);
    }

    /**
     * 个股分时K线详情
     * @param stockCode
     * @return
     */
    @Override
    public R<List<Stock4MinuteDomain>> stockScreenTimeSharing(String stockCode) {
        DateTime lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now());

        Date lastDate = lastDate4Stock.toDate();
        Date openDate = DateTimeUtil.getOpenDate(lastDate4Stock).toDate();

        //mock
        String mockDate="20220106142500";
        lastDate = DateTime.parse(mockDate, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();

        String openDateStr="20220106093000";
        openDate=DateTime.parse(openDateStr, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();

        List<Stock4MinuteDomain> result = stockRtInfoMapper.stockScreenTimeSharing(stockCode,openDate,lastDate);
        return R.ok(result);
    }

}